/*
 * @Author: zt 2993721164@qq.com
 * @Date: 2025-08-04 12:22:32
 * @LastEditors: zt 2993721164@qq.com
 * @LastEditTime: 2025-08-14 17:30:00
 * @FilePath: /yyshort/lib/pages/foryou/widgets/custom_icon_button.dart
 * @Description: 带isSelected属性的自定义图标按钮
 */
import 'package:flutter/material.dart';

enum IconState { normal, selected }

class CustomIconButton extends StatefulWidget {
  final String normalAsset;
  final String selectedAsset;
  final Function(bool) onTap;
  // 新增isSelected属性，支持外部控制初始状态
  final bool? isSelected;
  // 是否允许内部切换状态（默认允许）
  final bool enableToggle;

  const CustomIconButton({
    Key? key,
    required this.normalAsset,
    required this.selectedAsset,
    required this.onTap,
    this.isSelected,
    this.enableToggle = true,
  }) : super(key: key);

  @override
  State<CustomIconButton> createState() => _CustomIconButtonState();
}

class _CustomIconButtonState extends State<CustomIconButton> {
  late IconState _currentState;

  @override
  void initState() {
    super.initState();
    // 根据外部传入的isSelected初始化状态
    if (widget.isSelected != null) {
      _currentState = widget.isSelected!
          ? IconState.selected
          : IconState.normal;
    } else {
      _currentState = IconState.normal;
    }
  }

  // 当外部isSelected变化时更新内部状态
  @override
  void didUpdateWidget(covariant CustomIconButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isSelected != oldWidget.isSelected &&
        widget.isSelected != null) {
      setState(() {
        _currentState = widget.isSelected!
            ? IconState.selected
            : IconState.normal;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // 如果允许内部切换状态，则更新状态
        if (widget.enableToggle) {
          setState(() {
            _currentState = _currentState == IconState.normal
                ? IconState.selected
                : IconState.normal;
          });
        }
        // 回调中返回当前选中状态
        widget.onTap(_currentState == IconState.selected);
      },
      child: Image.asset(
        _currentState == IconState.normal
            ? widget.normalAsset
            : widget.selectedAsset,
        width: 32,
        height: 32,
      ),
    );
  }
}
